const os = require('os');
const fs = require('fs').promises;
const path = require('path');

async function checkDirectoryExists(dirPath) {
    try {
        const stat = await fs.lstat(dirPath);
        return stat.isDirectory();
    } catch (err) {
        return false;
    }
}

async function getAllFilesInDirectory(dirPath, extensions, blacklistDirs, fileList = []) {
    const entries = await fs.readdir(dirPath, { withFileTypes: true });
    for (const entry of entries) {
        const fullPath = path.join(dirPath, entry.name);

        // 检查当前路径是否在黑名单目录中，黑名单目录可以是部分路径
        // console.log(`entry = `, entry, `blacklistDirs = `, blacklistDirs);
        if (entry.isDirectory() && blacklistDirs.includes(entry.name)) {
            continue;
        }

        if (entry.isDirectory()) {
            await getAllFilesInDirectory(fullPath, extensions, blacklistDirs, fileList);
        } else if (entry.isFile() && extensions.includes(path.extname(entry.name).toLowerCase())) {
            fileList.push(fullPath);
        }
    }
    return fileList;
}

async function getAllDirsInDirectory(dirPath) {
    let dirList = [];
    try {
        const entries = await fs.readdir(dirPath, { withFileTypes: true });
        for (const entry of entries) {
            if (entry.isDirectory()) {
                dirList.push(entry.name);
            }
        }
    } catch (error) {
        // console.error('An error occurred while reading the directory:', error);
        dirList = null;
    }
    return dirList;
}

function getUserDataPath(appName) {
    // let appName = 'labelapp';
    let userDataPath;
    const userHomeDir = os.homedir();
    switch (process.platform) {
        case 'darwin': // macOS
            userDataPath = path.join(userHomeDir, 'Library', 'Application Support', appName);
            break;
        case 'win32': // Windows
            userDataPath = path.join(process.env.APPDATA, appName);
            break;
        default:
            userDataPath = path.join(userHomeDir, `.config`, `${appName}`); // Linux and others
    }
    return userDataPath;
}

module.exports = { getAllFilesInDirectory, getAllDirsInDirectory, checkDirectoryExists, getUserDataPath };
